package com.kehutong.basic.annex.service;

import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.util.Enums;
import org.coraframework.util.Objects;
import com.kehutong.basic.annex.entity.BasicAnnex;
import com.kehutong.basic.annex.enums.BusinessType;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.common.util.Token;

@WebService("/basic/annex/service")
public class BasicAnnexService {

    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private FileUrlConfig fileUrlConfig;

    public Object listPage(JSONObject jsonObject) {
        String businessType = jsonObject.getString("businessType");
        String businessId = jsonObject.getString("businessId");
        if (Objects.isEmpty(businessType) && Objects.isEmpty(businessId)) {
            return Result.error(0, "请输入必填参数");
        }

        return Result.success(jdbcSession.findPage(BasicAnnex.class)
                                         .eq(jsonObject, "businessType", "businessId")
                                         .eq("deleted", false)
                                         .order("createTime", "desc")
                                         .page(jsonObject)
                                         .exe());
    }

    @ReqMapping("/list/save")
    public Object listSave(JSONObject jsonObject){
        String uuid = jsonObject.getString("uuid");
        String username = jsonObject.getString("username");
        JSONArray jsonArray = jsonObject.getJSONArray("fileList");
        BusinessType businessType = Enums.getEnum(BusinessType.class, jsonObject.getString("businessType"));
        String businessId = jsonObject.getString("businessId");

        if (Objects.nonEmpty(uuid) && Objects.nonEmpty(username) && Objects.nonEmpty(jsonArray) && Objects.nonNull(businessType) && Objects.nonEmpty(businessId)) {
            for (int i = 0; i < jsonArray.size(); i++) {
                BasicAnnex basicAnnex = Pool.newInstance(BasicAnnex.class, String.valueOf(jsonArray.get(i)));
                basicAnnex.setUploadNo(uuid);
                basicAnnex.setUploadName(username);
                basicAnnex.setBusinessType(businessType);
                basicAnnex.setBusinessId(businessId);
                save(basicAnnex);
            }
            return Result.success();
        }

        return Result.error(0, "参数有误");
    }

    public Object del(BasicAnnex annex){

        if (Objects.isNull(annex)) {
            return Result.error(0, "删除失败，不存在该记录");
        }

        annex.setDeleted(true);
        jdbcSession.updateById(annex);

        try {
            fileUrlConfig.post("/file/delete", http -> {
                http.addParam("id", annex.getId());
            });
        }catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }

    public Object batchDel(JSONObject jsonObject){
        JSONArray array = jsonObject.getJSONArray("fileIds");
        if (Objects.isEmpty(array)) {
            return Result.error(0, "请选择需要删除的文件");
        }

        array.forEach(id -> {
            BasicAnnex annex = Pool.get(BasicAnnex.class, String.valueOf(id));
            if (Objects.nonNull(annex) && !annex.isDeleted()) {
                annex.setDeleted(Boolean.TRUE);
                jdbcSession.updateById(annex);
            }
        });

        try {
            fileUrlConfig.post("/file/batch/delete", http -> {
                JSONObject tempJson = new JSONObject();
                tempJson.put("ids", array);
                http.setBody(tempJson.toJSONString());
            });
        }catch (Exception e) {
            e.printStackTrace();
        }

        return Result.success();
    }

    public Object saveAnnex(Token token, JSONObject jsonObject){
        JSONObject tempJson = jsonObject.getJSONObject("businessType");
        if (Objects.isEmpty(tempJson)) {
            return Result.error(0, "请填写业务类型");
        }

        String id = jsonObject.getString("id");
        String businessId = jsonObject.getString("businessId");
        BusinessType businessType = Enums.getEnum(BusinessType.class, tempJson.getString("id"));
        if (Objects.isEmpty(id)|| Objects.isEmpty(businessId) || Objects.isNull(businessType)) {
            return Result.error(0, "请填写必要参数");
        }

        BasicAnnex annex = Pool.newInstance(BasicAnnex.class, id);
        annex.setBusinessId(businessId);
        annex.setBusinessType(businessType);
        annex.setRemarks(jsonObject.getString("remarks"));
        annex.setUploadNo(token.getUuid());
        annex.setUploadName(token.getUsername());

        return save(annex);
    }

    private Object save(BasicAnnex annex) {
        JSONObject tempJson;
        try {
            tempJson = fileUrlConfig.post("/file/get", http -> {
                http.addParam("id", annex.getId());
            });
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(0, e.getMessage());
        }

        if (tempJson.getInteger("code") == 200) {
            JSONObject temp = tempJson.getJSONObject("data");
            String name = temp.getString("name");
            if (Objects.isEmpty(name)) {
                return Result.error(0, "名称为空");
            }

            annex.setName(name.substring(0, name.lastIndexOf(".")));
            annex.setContentType(name.substring(name.lastIndexOf(".") + 1));
            annex.setSize(temp.getLong("size"));
            annex.setUploadTime(temp.getString("createTime"));

            jdbcSession.insert(annex);

            return Result.success();
        } else {
            return Result.error(0, "保存失败，请重试");
        }
    }
}
